function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function update_owner(sel) {
  $("input[name='owner']").val($(sel).val());
  $("#owner-span").html($(sel).val());
}

function show_my_accounts() {
  var owner = $.trim($("input[name='owner']").val());
  if (owner == "") {
    alert("You must tell me who you are!!!");
    return;
  }
  $("#info-div").html("<iframe id='info-frame'></iframe>");
  $("#info-frame").attr('src',
                        sprintf("stats/?player=%s&db=taras_race&user=taras-race&passwd=mhxzkhl", owner));
}

function add_to_db() {
    if ($("#account-table tr").size() == 0) {
        alert("I see no data in below, do you?");
        return;
    }
    var owner = $.trim($("#owner-span").html());
    var sql = "insert into owner values ";
    var accounts = new Array();
    $("#account-table tr").each(function(index, item) {
        if (index != 0) {
            sql += ', ';
        }
        sql += sprintf('("%s", "%s", "%s")',
                       owner,
                       $.trim($(item).find("td:first").html()),
                       $.trim($(item).find("td:last").html())
                      );
        accounts.push($.trim($(item).find("td:first").html()));
    });

    sql += " on duplicate key update passwd=values(passwd)";

    // check for conflicts in DB
    $.ajax({
        url: "race.php?func=check_confilict",
        data: {'accounts': accounts,
               'claim': owner},
        success: function(data) {
            if (data != "OK") {
                alert(data);
            } else {
                $.ajax({
                    url: "race.php?func=insert",
                    data: {'sql': sql},
                    type: 'POST',
                    async:false,
                    success: function(data) {
                        alert(data);
                    },
                    error: function(data, status) {
                        alert("failed: " + status);
                    }
                });
            }
        }
    });


}

function before_add_to_db() {
  try {
    var owner = $.trim($("#owner-span").html());
    if (owner == "") {
      alert('You tell me who you are!');
      return;
    }

    $.ajax({url: "race.php?func=check_player",
            data: {'owner': owner},
            async:false,
            success: function(data) {
              if (!isNumber(data) || parseInt(data) == 0) {
                if (confirm("Player ID " + owner + " doesn't exist in DB, create?")) {
                  add_to_db();
                }
              }
              else {
                add_to_db();
              }
            },
            error: function(data) {
              alert('Failed to contect DB, pray and try again later');
            }
           });
  } catch(err) {
    alert('Exception:' + err);
  }
}

$(document).ready(function() {
  try {
    // Events
    $("#add-to-db").click(before_add_to_db);

    // Init controls
    $("input[name='owner']").val($("select[name='owner-exist'] option").eq(0).html());
  } catch(err) {
    alert('exception: ' + err);
  }
});
